package com.d_project.qrcode.model {

    /**
     * QRAlphaNum
     * @author Kazuhiko Arase 
     */
    internal class QRAlphaNum extends QRData {
    
    	private static const CHARCODE_A:int = 'A'.charCodeAt(0);
    	private static const CHARCODE_Z:int = 'Z'.charCodeAt(0);
    	private static const CHARCODE_0:int = '0'.charCodeAt(0);
    	private static const CHARCODE_9:int = '9'.charCodeAt(0);
    	
    	public function QRAlphaNum(data : String) {
    		super(Mode.MODE_ALPHA_NUM, data);
    	}
    	
    	public override function write(buffer : BitBuffer) : void {
    
    		var i 	: int 		= 0;
            var s 	: String 	= getData();
            var len	:int 		= s.length;
    		while (i + 1 < len) {
    			buffer.put(getCode(s.charAt(i) ) * 45 + getCode(s.charAt(i + 1) ), 11);
    			i += 2;
    		}
    		
    		if (i < len) {
    			buffer.put(getCode(s.charAt(i) ), 6);
    		}
    	}
    	
    	public override function getLength() : int {
    		return getData().length;
    	}
    
    	private static function getCode(c : String) : int {
            var code : int = c.charCodeAt(0);
    		if (CHARCODE_0 <= code && code <= CHARCODE_9 ) {
    			return code - CHARCODE_0;
    		} else 
    		if (CHARCODE_A <= code && code <= CHARCODE_Z ) {
    			return code - CHARCODE_A + 10;
    		} else {
    			switch (c) {
    			case ' ' : return 36;
    			case '$' : return 37;
    			case '%' : return 38;
    			case '*' : return 39;
    			case '+' : return 40;
    			case '-' : return 41;
    			case '.' : return 42;
    			case '/' : return 43;
    			case ':' : return 44;
    			default :
    				throw new Error("illegal char :" + c);
    			}
    		}
    		throw new Error();
    	}	
    	/*
        private static function getCharCoder(c : String) : int {
            return c.charCodeAt(0);
        }
        */
    }
}